package cz.cvut.kadledav.paa.knapsack.util;

import cz.cvut.kadledav.paa.knapsack.bo.ComputedInstanceSolution;
import cz.cvut.kadledav.paa.knapsack.bo.InstanceSolution;

import java.util.List;
import java.util.Map;

/**
 * User: David Kadlecek
 * Date: 8.10.13
 */
public class SolutionUtil {

    public static long computeAverageTime(List<ComputedInstanceSolution> computedSolutions) {
        long sum = 0;
        for (ComputedInstanceSolution computedSolution : computedSolutions) {
            sum += computedSolution.getTime();
        }
        return sum / computedSolutions.size();
    }

    public static double computeAvgRelativeDeviance(Map<Integer, InstanceSolution> solutionMap, List<ComputedInstanceSolution> computedSolutions) {
        double relativeSum = 0;
        for (ComputedInstanceSolution computedSolution : computedSolutions) {
            InstanceSolution solution = solutionMap.get(computedSolution.getInstanceId());
            relativeSum += computeRelativeDeviance(solution, computedSolution);
        }
        return relativeSum/(double)computedSolutions.size();
    }

    /**
     * ( C(OPT)-C(APX) ) / C(OPT)
     *
     * @param correct          - OPT
     * @param computedSolution - APX
     * @return
     */
    public static double computeRelativeDeviance(InstanceSolution correct, ComputedInstanceSolution computedSolution) {
        return ((double) (correct.getPrice() - computedSolution.getPrice())) / (double) correct.getPrice();
    }

    public static double computeMaxRelativeDeviance(Map<Integer, InstanceSolution> solutionMap, List<ComputedInstanceSolution> computedSolutions) {
        double maxDeviation = 0;
        for (ComputedInstanceSolution computedSolution : computedSolutions) {
            InstanceSolution solution = solutionMap.get(computedSolution.getInstanceId());
            double deviation = computeRelativeDeviance(solution, computedSolution);
            if(deviation > maxDeviation){
                maxDeviation = deviation;
            }
        }
        return maxDeviation;
    }
}
